package com.loongtech.bi.manager.system;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.loongtech.bi.entity.system.EntityBiServer;
import com.loongtech.bi.entity.system.EntitySysRoleServer;
import com.loongtech.core.jpa.manager.ManagerBase;

@Service("sysRoleServerManager")
public class SysRoleServerManager extends ManagerBase<EntitySysRoleServer>
{
	private static final long	serialVersionUID = 8L;
	@Autowired
	private BiServerManager		serverManager;

	/**
	 * 获取一个角色当前已经被授权的服务器标识
	 * @param roleId
	 * @return
	 */
	public Set<String> getRoleServerSet(int roleId)
	{
		Set<String> set = new HashSet<String>();
		List<EntitySysRoleServer> list = findBy(EntitySysRoleServer.K.roleId, roleId);
		if (null != list && !list.isEmpty())
		{
			for (EntitySysRoleServer server : list)
			{
				set.add(server.getServerId());
			}
		}
		return set;
	}

	/**
	 * 获得角色当前归属的服务器列表
	 * @param roleId
	 * @return
	 */
	public List<EntityBiServer> getRoleServerList(int roleId)
	{
		List<EntityBiServer> list = new ArrayList<EntityBiServer>();
		for (EntitySysRoleServer info : findBy(EntitySysRoleServer.K.roleId, roleId))
		{
			EntityBiServer func = serverManager.get(info.getServerId());
			if (null != func)
			{
				list.add(func);
			}
		}
		return list;
	}

	/**
	 * 删除一条记录
	 * @param roleId
	 * @param serverId
	 * @return
	 */
	public boolean removeByRoleIdAndServerId(int roleId, String serverId)
	{
		EntitySysRoleServer entity = getBy(EntitySysRoleServer.K.roleId, roleId, EntitySysRoleServer.K.serverId, serverId);
		if (null != entity)
		{
			removeById(entity.getId());
			return true;
		}
		return false;
	}

	/**
	 * 插入一条记录
	 * @param roleId
	 * @param serverId
	 * @return
	 */
	public boolean insertByRoleIdAndServerId(int roleId, String serverId)
	{
		EntitySysRoleServer entity = getBy(EntitySysRoleServer.K.roleId, roleId, EntitySysRoleServer.K.serverId, serverId);
		if (null == entity)
		{
			entity = new EntitySysRoleServer();
			entity.setRoleId(roleId);
			entity.setServerId(serverId);
			persist(entity);
			return true;
		}
		return false;
	}
}
